package org.demo.warehouse.common.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.util.StringUtils;

import java.util.Locale;

/**
 * @author zgc
 * @since 2021/12/16
 */
@Data
@Accessors(chain = true)
public class PageParam {
    private String sort;
    private String order;
    private Integer limit;
    private Integer offset;
    private Integer type;

    public <T> QueryWrapper<T> getWrapper() {
        QueryWrapper<T> wrapper = new QueryWrapper<>();
        if (type != null) {
            wrapper.ne("type", type);
        }
        return StringUtils.hasText(sort) ? wrapper.orderBy(true, "asc".equals(order), humpToUnderline(sort)) :
                wrapper.orderByDesc("id");
    }

    public int getPage() {
        return offset / limit + 1;
    }

    public static String humpToUnderline(String para) {
        StringBuilder sb = new StringBuilder(para);
        int temp = 0;
        if (!para.contains("_")) {
            for (int i = 0; i < para.length(); i++) {
                if (Character.isUpperCase(para.charAt(i))) {
                    sb.insert(i + temp, "_");
                    temp += 1;
                }
            }
        }
        return sb.toString().toLowerCase();
    }

}
